package cn.icanci.loopstack.bic.sdk;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import cn.icanci.loopstack.bic.sdk.burying.BuryingBuilder;
import cn.icanci.loopstack.bic.sdk.properties.BicProperties;
import cn.icanci.loopstack.bic.sdk.system.SystemConstant;
import cn.icanci.loopstack.bic.sdk.thread.BicDataCachePool;
import cn.icanci.loopstack.bic.sdk.thread.BicEscalationService;
import cn.icanci.loopstack.bic.sdk.thread.TriggerThread;

/**
 * @author icanci
 * @since 1.0 Created in 2023/08/19 12:02
 */
@Configuration
@ComponentScan({ "cn.icanci.loopstack.bic.sdk" })
@EnableConfigurationProperties(BicProperties.class)
@AutoConfigureBefore
public class BicAutoConfiguration implements CommandLineRunner {
    @Resource
    private BicProperties        bicProperties;
    @Resource
    private BicEscalationService bicEscalationService;

    @Override
    public void run(String... args) throws Exception {
        // 对服务数据进行修正
        fixBicProperties();
        BuryingBuilder.setBicProperties(bicProperties);
        BicDataCachePool.setBicProperties(bicProperties);
        TriggerThread.setBicProperties(bicProperties, bicEscalationService);
    }

    private void fixBicProperties() {
        long maxBatchSubmitTime = bicProperties.getMaxBatchSubmitTime();
        if (maxBatchSubmitTime <= 0 || maxBatchSubmitTime > SystemConstant.MAX_BATCH_SUBMIT_TIME) {
            bicProperties.setMaxBatchSubmitTime(SystemConstant.MAX_BATCH_SUBMIT_TIME);
        }

        long maxBatchSize = bicProperties.getMaxBatchSize();
        if (maxBatchSize <= 0 || maxBatchSize > SystemConstant.MAX_BATCH_SIZE) {
            bicProperties.setMaxBatchSize(SystemConstant.MAX_BATCH_SIZE);
        }
    }
}
